//
//  YuanXinCamera.m
//  YuanXinCamera
//
//  Created by 晏德智 on 16/8/18.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "ImagePickerManager.h"
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTUtils.h>
#import <React/RCTImageLoader.h>
#import "TZImagePickerController.h"
#import "PhotoFilterViewController.h"
#import "VideoFilterViewController.h"
#import "Constants.h"
#import "NSObject+AssetsImageManager.h"
#define kAdeleImage @"Bigright"

typedef NS_ENUM(NSUInteger, CameraType) {
    CameraTypePhoto,
    CameraTypeVideo,
    CameraShowPhoto,
    CameraShowVideo
};

@interface ImagePickerManager()<UINavigationControllerDelegate>

/**
 *  返回选择结果类型
 */
@property (nonatomic, strong) NSString *resultContentType;

@property (nonatomic, retain) RCTPromiseResolveBlock success;

@property (nonatomic, retain) RCTPromiseRejectBlock  error;

@property (nonatomic, strong) NSString *tagString;

@end

@implementation ImagePickerManager

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE();

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

/**
 *  调用照像机
 *
 *  @param NSDictionary
 *
 *  @return
 */
RCT_EXPORT_METHOD(showImagePicker:(NSDictionary *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    self.success = resolve;
    self.error = reject;
    [self mappingParameters:options];
    
}

RCT_EXPORT_METHOD(launchCamera:(NSDictionary *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    self.success = resolve;
    self.error = reject;
    
    if ([RCTConvert NSUInteger:options[@"IsCamera"]]) {
        
        [self callVideoCamere:options];
        
    }else {
        [self callPhotoCamere:options];
    }
}

RCT_EXPORT_METHOD(launchImageLibrary:(NSDictionary *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    self.success = resolve;
    self.error = reject;
    
    if ([RCTConvert NSUInteger:options[@"IsChoose"]]) {
        
        [self showVideoCamere:options];
        
    }else {
        [self showPickPhoto:options];
    }
}

- (void)mappingParameters:(NSDictionary *)options{
    
    self.resultContentType = [RCTConvert NSString:options[@"resultType"]];
    CameraType cameraType = [RCTConvert NSUInteger:options[@"CameraType"]];
    self.tagString = [RCTConvert NSString:options[@"tagString"]];
    switch (cameraType) {
        case CameraTypePhoto:
            [self callPhotoCamere:options];
            break;
        case CameraTypeVideo:
            [self callVideoCamere:options];
            break;
        case CameraShowPhoto:
            [self OldshowPickPhoto:options];
            break;
        case CameraShowVideo:
            [self showVideoCamere:options];
            break;
        default:
            
            break;
    }
    
}


//老的选照片返回参数需要
- (void)OldshowPickPhoto:(NSDictionary *)options {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount: [RCTConvert NSInteger:options[@"maxCount"]]
                                                                                        columnNumber:[RCTConvert NSInteger:options[@"columnNumber"]] delegate:nil];
    
    
    imagePickerVc.albumPhotoName = [RCTConvert NSString:options[@"photoAlbumName"]];
    imagePickerVc.allowTakePicture =  [RCTConvert NSInteger:options[@"isShowCamera"]]; // 在内部显示拍照按钮
    // 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor redColor];
    //     imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    //     imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    // YES照片排列按修改时间升序   如果为NO 最近照片在前面拍照按钮在左边
    imagePickerVc.sortAscendingByModificationDate = NO;
    
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    
    
    UIViewController *controller = RCTKeyWindow().rootViewController;
    
    Wk(weakSelf)
    
    __block NSMutableArray *dataArray;
    // 通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    
        NSMutableArray *pathArr = [[NSMutableArray alloc] init];
        NSMutableArray *dataArr = [[NSMutableArray alloc] init];
        for (int i = 0; i < assets.count;  i++) {
            
            [pathArr addObject:[self getAssetURLstrFromAsset:assets[i]]];
            
            NSData*imageData=UIImageJPEGRepresentation(photos[i], 0.3);
            NSString *base64Encoded = [imageData base64EncodedStringWithOptions:0];
            
            [dataArr addObject:base64Encoded];
            
        }
        
        
        if (dataArr.count == assets.count &&  pathArr.count == assets.count){
            
            if (weakSelf.success) {
                
                if([weakSelf.resultContentType
                    isEqualToString:@"json"]){
                    
                    NSData *jsonPathData = [NSJSONSerialization dataWithJSONObject:pathArr options:NSJSONWritingPrettyPrinted error:nil];
                    NSString *jsonPath = [[NSString alloc] initWithData:jsonPathData encoding:NSUTF8StringEncoding];
                    
                    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataArr options:NSJSONWritingPrettyPrinted error:nil];
                    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                    weakSelf.success(@{@"data": jsonStr, @"FilePath":jsonPath,@"tag": _tagString});
                }else{
                    weakSelf.success(@{@"data": dataArr, @"FilePath":pathArr,@"tag": _tagString});
                }
            }
        }
        
    }];
    
    
    [controller presentViewController:imagePickerVc animated:YES completion:nil];
}

/**
 *  调用小视频功能
 *
 *  @param NSDictionary {@"maxSecond":@"6",@"videoAlumName":@""};
 @"maxSecond"->最长录制秒数（NSInteger）   @"videoAlumName"->创建的相册名字，默认项目名称,@"smallImageWidth":@""}
 0->照片  1->视频
 *  @return @{@“filePath”:@"本地相册视频路径",@"type":@"1"}
 */

- (void)callVideoCamere :(NSDictionary *)options{
    
    UIViewController *controller = RCTKeyWindow().rootViewController;
    VideoFilterViewController *videoVc = [VideoFilterViewController new];
    
    videoVc.maxRecorderTime = [RCTConvert NSInteger:options[@"maxSecond" ]];
    videoVc.albumName = [RCTConvert NSString:options[@"videoAlumName"]];
    
    Wk(weakSelf)
    videoVc.completBlock = ^(NSURL *assetURL)
    {
        id asset = [self getAssetFromAssetURL:assetURL];
        NSString *filePath = [self getAssetURLstrFromAsset:asset];
        if (weakSelf.success) {
            weakSelf.success(@{@"filePath":filePath,@"type":@(1)});
        }
    };
    [controller presentViewController:videoVc animated:YES completion:nil];

}


/**
 *  调用拍照功能
 *  0->照片  1->视频
 *  @return NSDictionary @{@"filePath":@"照片存在本地相册路径",@"type":@"0"}
 */

- (void)callPhotoCamere:(NSDictionary *)options {
    
    UIViewController *controller = RCTKeyWindow().rootViewController;
    PhotoFilterViewController *photoVC = [PhotoFilterViewController new];
    
    photoVC.albumName = [RCTConvert NSString:options[@"photoAlbumName"]];
    
    Wk(weakSelf)
    photoVC.completBlock = ^(NSURL *assetURL, UIImage *coverImage)
    {
        id asset = [self getAssetFromAssetURL:assetURL];
        NSString *filePath = [self getAssetURLstrFromAsset:asset];
        if ( weakSelf.success) {
            weakSelf.success(@{@"filePath":filePath,@"type":@(0)});
        }
    };
    [controller presentViewController:photoVC animated:YES completion:nil];
    
}


/**
 *  调用选择照片
 *
 *  @param NSDictionary { maxCount:最多选几张，photoAlbumName:内部照相机创建相册名字，showTakePhotoBtn:是否有内部照相机， columnNumber:内部相册分几列显示,@"smallImageWidth":@""} ;
 0->照片  1->视频
 *  @return NSArray @[@{@"type":@"0"，@“filePath” :@""},];
 */
- (void)showPickPhoto:(NSDictionary *)options {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount: [RCTConvert NSInteger:options[@"maxCount"]]
                                                                                        columnNumber:[RCTConvert NSInteger:options[@"columnNumber"]] delegate:nil];
    
    
    imagePickerVc.albumPhotoName = [RCTConvert NSString:options[@"photoAlbumName"]];
    imagePickerVc.allowTakePicture =  [RCTConvert NSInteger:options[@"isShowCamera"]]; // 在内部显示拍照按钮
    // 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor redColor];
    //     imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    //     imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    // YES照片排列按修改时间升序   如果为NO 最近照片在前面拍照按钮在左边
    imagePickerVc.sortAscendingByModificationDate = NO;
    
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    
    
    UIViewController *controller = RCTKeyWindow().rootViewController;
    
    Wk(weakSelf)
    
    __block NSMutableArray *dataArray;
    // 通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        dataArray = [NSMutableArray new];
        for (int i = 0; i < assets.count; i ++) {
            
            NSString *assetURLstr = [self getAssetURLstrFromAsset:assets[i]];
            NSDictionary *temDict = @{@"type":@"0",@"filePath":assetURLstr};
            [dataArray addObject:temDict];
            
            if (dataArray.count == assets.count){
                
                if (weakSelf.success) {
                    
                    weakSelf.success(dataArray);
                }
            }
        }
        
    }];
    
    
    [controller presentViewController:imagePickerVc animated:YES completion:nil];
}

/**
 *  调用选择视频
 *
 *  @param NSDictionary { maxCount:做多选几张，videoAlumName:内部照相机创建相册名字，showTakePhotoBtn:是否有内部照相机， columnNumber:内部相册分几列显示,@"smallImageWidth":@""} ;
 *   0->照片  1->视频
 *  @return NSArray @[@{@"type":@"1"，@“filePath” :@""},,];
 */
- (void)showVideoCamere:(NSDictionary *)options {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount: [RCTConvert NSInteger:options[@"maxCount"]]
                                                                                        columnNumber:[RCTConvert NSInteger:options[@"columnNumber"]] delegate:nil];
    
    
    imagePickerVc.albumVideoName = [RCTConvert NSString:options[@"videoAlumName"]];
    imagePickerVc.allowTakePicture =  [RCTConvert NSInteger:options[@"isShowCamera"]];
    
    // YES照片排列按修改时间升序   如果为NO 最近照片在前面拍照按钮在左边
    imagePickerVc.sortAscendingByModificationDate = NO;
    
    //照片和视频不能同时选
    imagePickerVc.allowPickingVideo = YES;
    imagePickerVc.allowPickingImage = NO;
    
    
    imagePickerVc.maxRecorderTime = [RCTConvert NSInteger:options[@"maxSecond" ]];
    
    imagePickerVc.didFinishPickingVideoHandle = ^(NSArray<UIImage *> *photos,NSArray *assets){
        
        
        NSMutableArray *dataArray = [NSMutableArray new];
        Wk(weakSelf)
        
        for (int i = 0; i <assets.count ; i++) {
            NSString *assetURLstr = [self getAssetURLstrFromAsset:assets[i]];
            NSDictionary *temDict = @{@"type":@"1",@"filePath":assetURLstr};
            [dataArray addObject:temDict];
            
            if (dataArray.count == assets.count){
                if (weakSelf.success) {
                    weakSelf.success(dataArray);
                }
            }
            
        }
        
        
    };
    UIViewController *controller = RCTKeyWindow().rootViewController;
    
    [controller presentViewController:imagePickerVc animated:YES completion:nil];
}

- (NSString *)getAssetURLstrFromAsset:(id)asset{
    
    if ([asset isKindOfClass:[ALAsset class]]) {
        //assets-library
        NSURL *assetURL =[asset valueForProperty:ALAssetPropertyAssetURL];
        NSString *imageUrl =[assetURL.absoluteString stringByReplacingOccurrencesOfString:assetURL.scheme withString:@"yuanxin-assets"];
        RCTLog(@"assets-library %@", assetURL.absoluteString);
        
        return imageUrl;
        
    }else if ([asset isKindOfClass:[PHAsset class]]){
        
        PHAsset *phAsset = (PHAsset *)asset;
        //return phAsset.localIdentifier;
        NSString *imageUrl = [NSString stringWithFormat:@"yuanxin-assets://%@",phAsset.localIdentifier];
        RCTLog(@"PHAsset %@", imageUrl);
        
        //[assetURL.absoluteString stringByReplacingOccurrencesOfString:assetURL.scheme withString:@"yuanxin-assets"];
        return imageUrl;
    }
    
    return nil;
}


@end

















